package functions;

import java.util.HashMap;

import util.FileClassLoader;


import connection.IrcConnection;
import connection.IrcEvent;
import connection.IrcFunction;

public class FunctionLoader implements IrcFunction {
	IrcConnection connection;
	HashMap<String, IrcFunction> loadedModules;
	
	public FunctionLoader() {
		loadedModules = new HashMap<String, IrcFunction>();
	}

	@SuppressWarnings("unchecked")
	public void eventPerformed(IrcEvent e) {
		String cmd=e.getFirstWord();
		if (cmd.equals(",modules")) {
			String mods="Loaded Modules: ";
			for (String s: loadedModules.keySet()) {
				mods += s+", ";
			}
			connection.privMsg(e.getTarget(), mods);
				
		} else if (cmd.equals(",loadmodule")) {
			if (e.getPrivRest() == null) {
				connection.privMsg(e.getTarget(), "not enough parameters");
				return;
			}
			String moduleName = "functions."+ e.getPrivRest().split(" ", 2)[0];
			if (loadedModules.containsKey(moduleName)) {
				connection.privMsg(e.getTarget(), "module already loaded: "+ moduleName);
				return;
			}
			String[] params=null;
			if (e.getPrivRest().length() > moduleName.length()) {
				params = e.getPrivRest().substring(moduleName.length()+1).split(" ");
			}
			
			FileClassLoader loader = new FileClassLoader();
			Class newClass=null;
			IrcFunction func;
			
			try {
				newClass = loader.loadClass(moduleName);
				func = (IrcFunction)newClass.newInstance();
			} catch (ClassNotFoundException e1) {
				connection.privMsg(e.getTarget(), "module not found");
				return;
			} catch (Exception e1) {
				e1.printStackTrace();
				return;
			}
			
			func.setIrcConnection(connection);
			System.out.println(1);
			if (params!=null)
				func.setParams(params);

			connection.privMsg(e.getTarget(), "module loaded: "+moduleName);
			loadedModules.put(moduleName, func);
			
		} else if (cmd.equals(",unloadmodule")) {
			if (e.getPrivRest() != null) {
				String moduleName = e.getPrivRest().split(" ")[0];
				if (loadedModules.get(moduleName) != null) {
					connection.removeEventListener(loadedModules.get(moduleName));
					loadedModules.remove(moduleName);
					connection.privMsg(e.getTarget(), "module unloaded: "+ moduleName);
				} else {
					connection.privMsg(e.getTarget(), "module not loaded");
				}
				
			} else {
				connection.privMsg(e.getTarget(), "not enough parameters");
			}
		}
				
	}

	@Override
	public void setIrcConnection(IrcConnection con) {
		connection = con;
		connection.addEventListener(this, "PRIVMSG");
	}

	@Override
	public void setParams(String[] params) {
	}

}
